package com.ruoyi.web.controller.business;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.dic.SexEnum;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.sun.jna.platform.win32.OaIdl;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 处方的药品信息Controller
 *
 * @author ruoyi
 * @date 2023-05-13
 */
@Controller
@RequestMapping("/system/history")
public class TPrescriptionHistoryInfoController extends BaseController {
    private String prefix = "system/history";

    @Autowired
    private ITPrescriptionHistoryInfoService tPrescriptionHistoryInfoService;

    @Autowired
    private ITPrescriptionRecordsService tPrescriptionRecordsService;

    @Autowired
    private ITDrugInfoService tDrugInfoService;

    @Autowired
    private ITPrescriptionDrugInfoService tPrescriptionDrugInfoService;

    @Autowired
    private ITPrescriptionNurseHisService tPrescriptionNurseHisService;


    @RequiresPermissions("system:history:view")
    @GetMapping()
    public String info() {
        return prefix + "/history";
    }

    /**
     * 查询处方的药品信息列表
     */
    @RequiresPermissions("system:history:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TPrescriptionHistoryInfo tPrescriptionHistoryInfo) {
        startPage();
        // Hisory表
        List<TPrescriptionHistoryInfo> hisList = tPrescriptionHistoryInfoService.selectTPrescriptionHistoryInfoList(tPrescriptionHistoryInfo);
        // 处方信息
        List<TPrescriptionHistoryInfo> list = tPrescriptionHistoryInfoService.selectOtherHistoryInfoList(tPrescriptionHistoryInfo);
        setDaysDetail(list);
        setDaysDetail(hisList);

        //判断当前是否查询已完成的状态
        if (tPrescriptionHistoryInfo.getStatus() != null && tPrescriptionHistoryInfo.getStatus() == 1) {
            // 当日新增处方
            list = list.stream().filter(e -> e.getStatus() == 1).collect(Collectors.toList());
            list.addAll(hisList);
        } else if (tPrescriptionHistoryInfo.getStatus() != null && tPrescriptionHistoryInfo.getStatus() == 4) {
            //历史未完结处方
            list = list.stream().filter(e -> e.getStatus() == 4).collect(Collectors.toList());
        }

        list.sort(new Comparator<TPrescriptionHistoryInfo>() {
            @Override
            public int compare(TPrescriptionHistoryInfo person1, TPrescriptionHistoryInfo person2) {
                return (int) (person1.getAdd_time().getTime() - person2.getAdd_time().getTime());
            }
        });
        return getDataTable(list);
    }

    private void setDaysDetail(List<TPrescriptionHistoryInfo> datas) {
        datas.stream().peek(e -> {
            int less = e.getDaysDetail() - e.getOver_days();
            e.setDaysDetailDesc(e.getDaysDetail() + "天余" + less);
            e.setCustomerSex(SexEnum.getByCode(e.getCustomerSex()));
        }).collect(Collectors.toList());
    }

    /**
     * 查询处方的药品信息列表
     */
    @RequiresPermissions("system:history:historyList")
    @PostMapping("/historyList")
    @ResponseBody
    public TableDataInfo historyList(TPrescriptionHistoryInfo tPrescriptionHistoryInfo) {
        startPage();
        List<TPrescriptionHistoryInfo> list = tPrescriptionHistoryInfoService.selectOtherHistoryInfoList(tPrescriptionHistoryInfo);
        return getDataTable(list);
    }

    /**
     * 导出处方的药品信息列表
     */
    @RequiresPermissions("system:history:export")
    @Log(title = "处方的药品信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TPrescriptionHistoryInfo tPrescriptionHistoryInfo) {
        List<TPrescriptionHistoryInfo> list = tPrescriptionHistoryInfoService.selectTPrescriptionHistoryInfoList(tPrescriptionHistoryInfo);
        ExcelUtil<TPrescriptionHistoryInfo> util = new ExcelUtil<TPrescriptionHistoryInfo>(TPrescriptionHistoryInfo.class);
        return util.exportExcel(list, "处方的药品信息数据");
    }

    /**
     * 新增处方的药品信息
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存处方的药品信息
     */
    @RequiresPermissions("system:history:add")
    @Log(title = "处方的药品信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TPrescriptionHistoryInfo tPrescriptionHistoryInfo) {
        if (tPrescriptionHistoryInfo.getCustomerSex().equals("男")) {
            tPrescriptionHistoryInfo.setCustomerSex("0");
        } else {
            tPrescriptionHistoryInfo.setCustomerSex("1");
        }
        return toAjax(tPrescriptionHistoryInfoService.insertTPrescriptionHistoryInfo(tPrescriptionHistoryInfo));
    }

    /**
     * 修改处方的药品信息
     */
    @RequiresPermissions("system:history:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        TPrescriptionHistoryInfo tPrescriptionHistoryInfo = tPrescriptionHistoryInfoService.selectTPrescriptionHistoryInfoById(id);
        mmap.put("tPrescriptionHistoryInfo", tPrescriptionHistoryInfo);
        return prefix + "/edit";
    }

    /**
     * 删除处方的药品信息
     */
    @RequiresPermissions("system:history:remove")
    @Log(title = "处方的药品信息", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(tPrescriptionHistoryInfoService.deleteTPrescriptionHistoryInfoByIds(ids));
    }

    /**
     * 展示处方信息
     */
    @RequiresPermissions("system:history:detail")
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap) {
        TPrescriptionRecords tPrescriptionRecords = tPrescriptionRecordsService.selectTPrescriptionRecordsById(id);
        mmap.put("tPrescriptionRecords", tPrescriptionRecords);
        mmap.put("pharmacyid", getSysUser().getUserId());
        mmap.put("dingdanfanhui",tPrescriptionRecords.getOver_days()==0);
        return prefix + "/info";
    }

    /**
     * 修改处方表
     */
    @RequiresPermissions("system:history:edit")
    @Log(title = "处方信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updatePrescription")
    @ResponseBody
    public AjaxResult updatePrescription(TPrescriptionRecords tPrescriptionRecords) {
        if (tPrescriptionRecords.getStatus() != null && (tPrescriptionRecords.getStatus().equals("4") || tPrescriptionRecords.getStatus().equals("3"))) {
            // 更新已完成天数
            TPrescriptionDrugInfo info = new TPrescriptionDrugInfo();
            info.setPrescriptionid(tPrescriptionRecords.getId());
            tPrescriptionDrugInfoService.updateOverDays(info);

            // 如果处方中存在注册类药品，则给护士添加一次注射记录
            TPrescriptionDrugInfo drugInfo = new TPrescriptionDrugInfo();
            drugInfo.setPrescriptionid(tPrescriptionRecords.getId());
            drugInfo.setDrugType("business_zsl");
            // 查询处方中注射类药品数量
            Tcount tcount = tPrescriptionNurseHisService.selectTPrescriptionZslDrugCount(drugInfo);
            if (tcount != null && tcount.getCounts() > 0) {
                // 处方中有注射类药品，则给护士添加一次注射记录
                TPrescriptionNurseHis tPrescriptionNurseHis = new TPrescriptionNurseHis();
                tPrescriptionNurseHis.setNurseid(getSysUser().getUserId());
                tPrescriptionNurseHis.setPrescriptionid(tPrescriptionRecords.getId());
                tPrescriptionNurseHis.setCrtime(new Date());
                tPrescriptionNurseHisService.insertTPrescriptionNurseHis(tPrescriptionNurseHis);
            }
        }

        tPrescriptionRecords.setLast_operate_time(DateUtils.getNowDate());
        return toAjax(tPrescriptionRecordsService.updateTPrescriptionRecords1(tPrescriptionRecords));
    }

    /**
     * yi`fa yao
     */
    @RequiresPermissions("system:history:edit")
    @Log(title = "处方信息", businessType = BusinessType.UPDATE)
    @PostMapping("/yifayao")
    @ResponseBody
    public AjaxResult yifayao(TPrescriptionRecords tPrescriptionRecords) {
        tPrescriptionRecords.setLast_operate_time(DateUtils.getNowDate());
        int i = tPrescriptionRecordsService.updateTPrescriptionRecords1(tPrescriptionRecords);
        // 查询未出结果的皮试纸的数量
        List<TPrescriptionRecords> tPrescriptionRecords1 =
                tPrescriptionRecordsService.selectCount(tPrescriptionRecords.getId());
        if (tPrescriptionRecords1.size() == 0) {
            // 减掉药品库存数量
            tPrescriptionRecordsService.updateNumber(tPrescriptionRecords.getId());
        }
        tPrescriptionHistoryInfoService.deleteTPrescriptionHistoryInfoById(tPrescriptionRecords.getId().toString());
        return toAjax(i);
    }


    /**
     * 查询当日营业额
     */
    @RequiresPermissions("system:history:edit")
    @Log(title = "当日营业额", businessType = BusinessType.UPDATE)
    @PostMapping("/yye")
    @ResponseBody
    public AjaxResult yye() {
        Tres res = tPrescriptionHistoryInfoService.getTodayAmount();
        return success(res);
    }

    /**
     * 查询当日退款额
     */
    @RequiresPermissions("system:history:edit")
    @Log(title = "当日退款额", businessType = BusinessType.UPDATE)
    @PostMapping("/jrtk")
    @ResponseBody
    public AjaxResult jrtk() {
        Tres res = tPrescriptionHistoryInfoService.getTodayTuikuanAmount();
        return success(res);
    }

}
